package com.lithium.parser;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.lithium.common.ActiveIngredient;
import com.lithium.common.Medication;
import com.lithium.common.MedicationCommentTitle;
import com.lithium.common.MedicationComments;
import com.lithium.dao.CustomDAO;

public class HTMLSimpleParser {

	/**
	 * @param args
	 */

	public static String file = "C:\\Users\\havena\\Downloads\\parsetest\\6080_172.htm";
	public static String directory = "C:\\Users\\havena\\Downloads\\parsetest\\";

	// private static CustomDAO customdao;

	// private static DataSource datasource;

	public static void main(String[] args) {

		int maxCount = 0;

		try {

			// ClassPathXmlApplicationContext context = new
			// ClassPathXmlApplicationContext(
			// "com/lithium/parser/parser-context.xml");

			// customdao = context.getBean("custom-dao", CustomDAO.class);

			FileWriter foutstream = new FileWriter("C:\\avenanew\\out.txt");
			BufferedWriter out = new BufferedWriter(foutstream);
			Properties properties = new Properties();

			URL url = ClassLoader
					.getSystemResource("com/lithium/parser/regex.properties");

			properties.load(new FileInputStream(new File(url.getFile())));

			File[] files = new File(directory).listFiles();

			// boolean token = false;

			System.out.println("Starting to pull htm files:");

			for (File file : files) {
				if (file.getName().indexOf("htm") > 0) {

					maxCount++;

					FileInputStream fstream = new FileInputStream(file);

					DataInputStream in = new DataInputStream(fstream);

					BufferedReader br = new BufferedReader(
							new InputStreamReader(in));

					String strLine;

					Pattern pattern_title = Pattern.compile(properties
							.getProperty("title.regex"));
					Pattern pattern_ingredient = Pattern.compile(properties
							.getProperty("ingrediente.regex"));

					Pattern pattern_ingredient_extra = Pattern
							.compile(properties
									.getProperty("ingrediente.extra.regex"));

					Pattern pattern_format = Pattern.compile(properties
							.getProperty("format.regex"));

					Pattern pattern_content_p = Pattern.compile(properties
							.getProperty("main.article.content.regex"));

					Pattern pattern_main_title = Pattern.compile(properties
							.getProperty("main.article.title.regex"));

					Pattern pattern_title_extra = Pattern.compile(properties
							.getProperty("title.extra.regex"));

					Medication med = new Medication();

					List<String> titles = new ArrayList<String>();

					List<String> content = new ArrayList<String>();

					List<MedicationComments> comments = new ArrayList<MedicationComments>();

					while ((strLine = br.readLine()) != null) {

						Matcher matcher = pattern_title.matcher(strLine);

						if (matcher.find()) {

							String tempstring = matcher.group(1);
							
							System.out.println(tempstring);

							Matcher matcher_extra = pattern_title_extra
									.matcher(tempstring);

							if (matcher_extra.matches()) {

								med.setTitle(matcher.group(1));

								med.setImg(matcher.group(2));

								med.setAlt_img_txt(matcher.group(3));

							} else {

								med.setTitle(tempstring);

							}

							continue;
						}

						matcher = pattern_format.matcher(strLine);

						if (matcher.find()) {

							// System.out.println("Formato =" +
							// matcher.group(1));
							med.setFormato(matcher.group(1));
							// med.formato = matcher.group(1);
							continue;
						}

						matcher = pattern_ingredient.matcher(strLine);

						if (matcher.find()) {

							System.out.println("ingrediente ="
									+ matcher.group(1));
							String tempString = removeChar(matcher.group(1),
									'(');
							tempString = removeChar(tempString, ')');

							matcher = pattern_ingredient_extra
									.matcher(tempString);

							if (matcher.matches()) {

								tempString = matcher.group(1);
								med.setIngrediente(tempString);

							} else {
								med.setIngrediente(tempString);
							}

							continue;
						}

						/*
						 * matcher = pattern_forma_farmac.matcher(strLine); if
						 * (matcher.find()) {
						 * 
						 * currentTitle = "Forma Farmaceutica";
						 * 
						 * System.out.println("\n\n\n" + currentTitle +
						 * "\n\n\n"); // Get all groups for this match /* for
						 * (int i=0; i<=matcher.groupCount(); i++) { String
						 * groupStr = matcher.group(i); }
						 * 
						 * continue; }
						 */

						// titulo match
						matcher = pattern_main_title.matcher(strLine);

						if (matcher.find()) {

							// comments.add(currentcomment);

							titles.add(matcher.group(1));

							continue;

						}

						matcher = pattern_content_p.matcher(strLine);
						if (matcher.find()) {

							// System.out.println(strLine);
							MedicationComments comment = new MedicationComments();
							comment.setMed_comment(matcher.group(1));
							comments.add(comment);
							content.add(matcher.group(1));
							continue;

						}

					}

					System.out.println("+--------------------+");
					System.out.println("filename:" + file.getName());
					System.out.println("number of titles:" + titles.size());
					System.out.print(med.toString());
					System.out.println("+--------------------+");

					// check if the ingredient is on the database.

					int count = 1;
					//
					Iterator<String> it = titles.iterator();
					while (it.hasNext()) {
						String title = it.next();
						out.write(title + "\n");
						// System.out.println(count + ".-" + title + " ");
						count++;
					}

					Iterator<MedicationComments> it2 = comments.iterator();
					while (it2.hasNext()) {
						MedicationComments cont = it2.next();
						out.write(cont + "\n");
						// System.out.println("title id :"
						// + cont.getMed_comment_title_id() + " ");
						System.out.println("contenidos :"
								+ cont.getMed_comment() + " ");
					}

					/*
					 * Iterator<String> it = titles.iterator(); int count = 1;
					 * while(it.hasNext()) {
					 * 
					 * String title = it.next(); System.out.println(count + ".-"
					 * +title + " "); count++;
					 * 
					 * }
					 */

					// Collection<String> test = article.values();

					// obtain an Iterator for Collection
					// Iterator itr = test.iterator();

					/*
					 * while (itr.hasNext()) { System.out.println(itr.next()); }
					 */
					in.close();

					// System.out.print(med.toString());

				} else {
					// System.out.println("File: " + file.getName());
				}

			}
			out.close();
			System.out.println(maxCount);

		} catch (Exception e) {

			System.err.println("Error: " + e.getMessage());
			e.printStackTrace();

		}

	}

	public static String removeChar(String s, char c) {

		String r = "";

		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) != c)
				r += s.charAt(i);
		}

		return r;
	}
}
